import React, { PureComponent, Fragment } from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Button,
  Tag,
  Modal,
  Form,
  message,
  Table,
  Radio,
  Input,
  Icon,
  Drawer,
  Row,
  Tree,
  Switch,
  Progress, DatePicker, Badge, Select, Popover, TreeSelect, Tooltip,
} from 'antd';
import MyPagination from '@/components/MyPagination';
import find from 'lodash/find';
import Loading from '@/components/Loading';
import {
  renderValveOpen,
  afterCloseModal,
  renderTreeNodes,
  popoverPrice,
  download,
  formateObjToParamStr,
  renderSignalIntensity,
  formateObjToParamStr2, getEW
} from '@/utils/utils';
import debounce from 'lodash/debounce';
import Detail from './../Owner/Detail';
import ReactDataGrid from 'react-data-grid';
import request from '@/utils/request';
import config from '../../config/config';
import AreaMap from "@/components/AreaMap";
const FormItem = Form.Item;
const Option = Select.Option;

const RadioButton = Radio.Button;

const RadioGroup = Radio.Group;

@connect(({ meter_abnormal, loading,global }) => ({
  meter_abnormal,
  global,
  loading: loading.models.meter_abnormal,
}))
@Form.create()
class BasicList extends PureComponent {
  constructor(props) {
    super(props);
    this.permissions = JSON.parse(sessionStorage.getItem('permissions'));
    this.state = {
      showAddBtn: find(this.permissions, { name: 'device_add_and_edit' }),
      showdelBtn: find(this.permissions, { name: 'device_delete' }),
      showPasswordBtn: find(this.permissions, { name: 'user_default_password_edit' }),
      user_password_reset: find(this.permissions, { name: 'user_password_reset' }),
      visible: false,
      done: false,
      page: 1,
      per_page: 30,
      username: '',
      editRecord: {},
      selectedRowKeys: [],
      all_vendors: [],
      data: [],
      all_protocols:[]
    };
  }


  componentDidMount() {

    const { dispatch } = this.props;
    const {
      meter_abnormal: { pageLoaded, scrollData },
    } = this.props;
    console.log('pageLoaded', pageLoaded);
    const table = document.querySelector('.react-grid-Canvas');
    if (pageLoaded) {
      setTimeout(() => {
        table.scrollTop = scrollData.y;
        table.scrollLeft = scrollData.x;
      }, 0);

    } else {
      const {
        meter_abnormal: { searchParams },
      } = this.props;
      console.log('searchParams', searchParams);
      dispatch({
        type: 'meter_abnormal/fetch',
        payload: searchParams,
        callback: () => {
          const { dispatch } = this.props;
          dispatch({
            type: 'meter_abnormal/changeLoaded',
          });
          dispatch({
            type: 'meter_abnormal/changeTableY',
          });


        },
      });
    }

    const that = this;
    request(`/all_vendors`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          all_vendors: response.data.data,
        });
      }

    });
    request(`/all_regions`, {
      method: 'GET',
    }).then((response) => {
      if (response.status === 200) {
        that.setState({
          data: response.data.data,
        });
      }

    });
    request(`/all_protocols`, {
      method: 'GET',
    }).then((response)=> {
      if(response.status===200){
        that.setState({
          all_protocols:response.data.data
        })
      }
    })
    window.addEventListener('resize', this.resize);
    table.addEventListener('scroll', debounce(this.scroll, 150));
  }

  scroll = (e) => {
    console.log('scroll');
    const { dispatch } = this.props;
    dispatch({
      type: 'meter_abnormal/changeScroll',
      payload: {
        x: e.target.scrollLeft,
        y: e.target.scrollTop,
      },
    });
  };

  resize = () => {
    const { dispatch } = this.props;

    // this.changeTableY();
    dispatch({
      type: 'meter_abnormal/changeTableY',
    });
  };

  changeTableY = () => {
    this.setState({
      tableY: document.querySelector('.bottom-analysis').getBoundingClientRect().top -
        document.querySelector('.custom-small-table').getBoundingClientRect().top - 50,
    });
  };

  componentWillUnmount() {
    console.log('componentWillUnmount');
    window.removeEventListener('resize', this.resize);
    return;
    const table = document.querySelector('.ant-table-body');
    table.removeEventListener('scroll', debounce(this.scroll, 300));
  }

  handleSearch = (values, cb) => {
    console.log('handleSearch', values);
    const that = this;
    const { dispatch } = this.props;
    dispatch({
      type: 'meter_abnormal/fetch',
      payload: {
        ...values,
      },
      callback() {
        console.log('handleSearch callback');
        if (cb) cb();
        const {
          meter_abnormal: { scrollData },
        } = that.props;
        const table = document.querySelector('.react-grid-Canvas');
        if(table){
          setTimeout(() => {
            table.scrollTop = 0;
            table.scrollLeft = scrollData.x;
          }, 0);
        }

      },
    });
  };

  renderSimpleForm() {
    const data = this.state.data;

    const {
      meter_abnormal: { searchParams },
    } = this.props;
    const form=this.props.form
    const getFieldDecorator=form.getFieldDecorator
    return (
      <Form layout="inline" className="search-form">
        <AreaMap form={form} searchParams={searchParams} getFieldDecorator={getFieldDecorator}/>

        <FormItem label={'日期'}>
          {getFieldDecorator('date', {
            initialValue: moment(searchParams.date),
          })(
            <DatePicker
              style={{width: '120px'}}
              allowClear={false}
              //disabledDate={disabledDate}
              format="YYYY-MM-DD"
            />
          )}
        </FormItem>
        <FormItem label="区域">
          {getFieldDecorator('region_id', {
            initialValue: searchParams.region_id?`${searchParams.region_id}$${searchParams.region_name}`:'',
          })(
            <TreeSelect
              style={{ width: '130px' }}
              allowClear
              treeDefaultExpandAll
              dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
              showSearch
            >
              {renderTreeNodes(data)}
            </TreeSelect>,
          )}
        </FormItem>
        <FormItem label="状态">
          {getFieldDecorator('status', {
            initialValue: searchParams.status,
          })(
            <Select style={{width:'160px'}}>
              <Option value="0">全部</Option>
              <Option value="-1">未上报</Option>
              <Option value="-2">漏报</Option>
              <Option value="-3">抄表失败</Option>
              <Option value="-4">错报</Option>
              {/* <Option value="-4">正常上报,用水量为0</Option> */}
            </Select>,
          )}
        </FormItem>
        <FormItem label="水表厂商">
          {getFieldDecorator('vendor_id', {
            initialValue: searchParams.vendor_id,
          })(
            <Select style={{ width: '100px' }} allowClear>
              {
                this.state.all_vendors.map((item, index) => {
                  return <Option key={index} value={item.id}>{item.name}</Option>;
                })
              }
            </Select>,
          )}
        </FormItem>
        <FormItem label="水表协议">
          {getFieldDecorator('protocol_id', {
            initialValue: searchParams.protocol_id,
          })(
            <Select style={{width:'160px'}} allowClear={true}  dropdownStyle={{ width: '200px' }}
                  >
              { this.state.all_protocols.map((item, key) => {
                return (
                  <Option key={item.id}  value={item.id.toString()}>{item.name}</Option>
                )
              }) }
            </Select>
          )}
        </FormItem>
        <FormItem label="连续异常天数">
          {getFieldDecorator('abnormal_days', {
            initialValue: searchParams.abnormal_days,
          })(   <Select style={{width:'100px'}}>
            {[{key:'全部',value:''},
              {key:'≥7天',value:'7'},
              {key:'≥15天',value:'15'},
              {key:'≥30天',value:'30'},
              {key:'≥100天',value:'100'},
            ].map(function(item,index) {
              return <Option key={index} value={item.value}>
                {item.key}
              </Option>
            })}
          </Select>)}
        </FormItem>
        <FormItem>
          <Button
            type="primary"
            icon='search'
            onClick={() => {
              const { form } = this.props;
              form.validateFields((err, fieldsValue) => {
                if (err) return;

                this.handleSearch({
                  page: 1,
                  per_page: searchParams.per_page,
                  ...fieldsValue,
                  date: moment(fieldsValue.date).format('YYYY-MM-DD'),
                  region_id:fieldsValue.region_id?fieldsValue.region_id.split('$')[0]:'',
                  region_name:fieldsValue.region_id?fieldsValue.region_id.split('$')[1]:'',
                });

              });
            }}
          >
            查询
          </Button>
          <Button style={{ marginLeft: 8 }} icon='redo' onClick={this.handleFormReset}>
            重置
          </Button>
          {
            find(this.permissions, { name: 'revenue_report_export' }) &&
            <Tooltip title={'导出前请查询一次 '}>
              <Button type={'primary'} className={'btn-cyan'}
                      style={{ marginLeft: 8 }} icon='export'
                      onClick={this.handleExport}>
                导出报表
              </Button>
            </Tooltip>
          }

        </FormItem>

      </Form>
    );
  }
  handleExport=()=>{
    const {
      meter_abnormal: { searchParams },
    } = this.props;
    const payload= {
      ...searchParams,
      company_ids:getEW(searchParams.company_ids),
      order_column:'abnormal_days',
      order_direction:'desc'
    }
    download(`${config.prefix}/meter_abnormal_report_files?Authorization=Bearer ${sessionStorage.getItem('token')}&${formateObjToParamStr2(payload)}`)
  }
  keyPress=(e)=>{
    let theEvent = e || window.event;
    let code = theEvent.keyCode || theEvent.which || theEvent.charCode;
    if (code === 13) {
      e.preventDefault();
      console.log('key press')
      const {
        meter_abnormal: { searchParams },
      } = this.props;
      const { form } = this.props;
      form.validateFields((err, fieldsValue) => {
        if (err) return;

        this.handleSearch({
          page: 1,
          per_page: searchParams.per_page,
          ...fieldsValue,
          date: moment(fieldsValue.date).format('YYYY-MM-DD'),
          region_id:fieldsValue.region_id?fieldsValue.region_id.split('$')[0]:'',
          region_name:fieldsValue.region_id?fieldsValue.region_id.split('$')[1]:'',
        });

      });
    }
  }

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
    this.handleSearch({
      company_ids:sessionStorage.getItem('company_sign'),
      company_id:'',
      region_id:"",
      region_name:'',
      date:moment().add(-1,'day').format("YYYY-MM-DD"),
      meter_number:'',
      online_status:'0',
      abnormal_days:'',
      user_number:'',
      vendor_id:'',
      protocol_id:'',
      address:'',
      status:'0',
      page: 1,
      per_page: 50,
    });
  };

  renderValueStatus=(val)=>{
    let status='success';
    let explain='';
    switch (val){
      case -5:
        status='error'
        explain= '接入异常'
        break;
      case -4:
        status='error'
        explain= '错报'
        break;
      case -3:
        status='error'
        explain='抄表失败'
        break;
      case -2:
        status='warning'
        explain= '漏报'
        break;
      case -1:
        status='warning'
        explain= '未上报'
        break;
      default:
        status='success'
        explain= '正常'
    }
    return (
      <p>
        <Badge status={status}/>{explain}
      </p>
    )
  }
  render() {
    const that = this;
    const {
      meter_abnormal: { data, loading, tableY, meta, searchParams, selectedRowKeys, status_count, total_consumption},
      global:{gridTableW}
    } = this.props;

    const defaultColumnProperties = {
      resizable: true,
    };
    const username = sessionStorage.getItem('username');
    const columns = [
      {
        name: '序号',
        width: 50,
        key: '_index',
        frozen:true,
        formatter: (event) => {
          const {
            meter_abnormal: { meta },
          } = this.props;
          return <p className={'index'}>{((meta.current_page - 1) * meta.per_page) + (event.value + 1)}</p>;
        },
      },
      {
        name: '户主姓名',
        width: 150,
        key: 'name',
        frozen:true,
      },
      {
        name: '手机号',
        width: 110,
        key: 'mobile',
      },
      {
        name: '户主地址',
        key: 'address',
        width: 200,
      },
      {
        name: '用水性质',
        width: 128,
        key: 'price_nature_name',
      },
      {
        name: '水表号',
        width: 130,
        key: 'meter_number',
      },
      {
        name: '状态',
        key: 'status',
        width: 60,
        formatter: (e) => {
          return that.renderValueStatus(e.value);
        },
      },
      {
        name: '上次有效上传时间',
        key: 'last_normal_upload_time',
        width: 150,
      },
      {
        name: '上次有效读数(m3)',
        key: 'last_normal_value',
        width: 130,
      },
      {
        name: '连续异常天数',
        key: 'abnormal_days',
        width: 100,
        formatter: (e) => {
          let abnormal_day=e.value;
          return <p
            className={(abnormal_day>=7)? (abnormal_day>=15)?'table-error table-status':'table-warm table-status' : ''}> {abnormal_day}
          </p>;
        },
      },
      {
        name: '备注',
        key: 'last_normal_value3',
        width: 110,
        formatter: (e) => {
            return <p
          className={(e.row.last_normal_value!=='-'&&e.row.last_normal_value>e.row.original_value)? 'table-error table-status' : ''}> {(e.row.last_normal_value!=='-'&&e.row.last_normal_value>e.row.original_value)?`水表存在倒流`:''}
            </p>;

        },
      },
      {
        name: '水表厂商名称',
        key: 'vendor_name',
        width: 130,
      },
      {
        name: '信号强度',
        key: 'signal_intensity',
        width: 80,
        formatter: (event) => {
          return renderSignalIntensity(event.value);
        },
      },
      {
        name: '操作',
        width: 100,
        key: 'right',
        classname:'operate',
        formatter: (event) => <Fragment>
          <Button
            className={'btn-cyan'}
            type="primary"
            size="small"
            icon="eye"
            onClick={(e) => {
              this.setState({
                editRecord: event.row,
                infoModal: true,
              });
            }
            }
          >详情
          </Button>
        </Fragment>,
      },
    ].map(c => ({  ...defaultColumnProperties,...c }));
    if(username==='唐永臻'||username==='amwares'){
      columns.splice(13,0,{
        name: 'SNR',
        key: 'snr',
        width: 60,
        formatter: (event) => {
          return <p>{Number(event.value)===-1?'异常':event.value}</p>
        },
      },)
    }
    let totalWidth = 0;
    for (let i = 0; i < columns.length; i++) {
      totalWidth += columns[i].width;
    }
    if(totalWidth<gridTableW){
      columns[columns.length-1].width=   columns[columns.length-1].width+gridTableW-totalWidth
    }

    return <div className="custom-card">
      <div className="table-title"><span className={'title-item'}>异常水表报表</span>
      </div>
      <div className="table-page table-page-flex">
        <div className="table-page-right">
          <div className="table-condition">{this.renderSimpleForm()}</div>
          <div  className={'table-data-content'}>
            <ReactDataGrid
              columns={columns}
              rowGetter={i => {
                return { ...data[i], _index: i };
              }}
              rowsCount={data.length}
              minHeight={tableY}
              rowSelection={{
                showCheckbox: false,
                enableShiftSelect: true,
                selectBy: {
                  indexes: selectedRowKeys,
                },
              }}
              onRowClick={
                (index,row) => {
                  console.log('row',row)
                  if(!row){
                    return
                  }
                  this.props.dispatch({
                    type: 'meter_abnormal/changeSelectRow',
                    payload: {
                      selectedIndex:[index],
                      row:row
                    },
                  });
                }
              }

            />
            {
              loading&&<Loading />
            }
          </div>
        </div>



      </div>
      <div className="table-pagination">
        <MyPagination searchCondition={{ ...searchParams }}
                      resetScrollY={() => {
                        console.log('resetScrollY');


                      }}
                      meta={meta} handleSearch={this.handleSearch}/>
      </div>
      <Drawer
        title={`${this.state.editRecord.name} 详情`}
        placement="right"
        destroyOnClose
        closable={false}
        onClose={() => {
          this.setState({
            infoModal: false,
            editRecord: {},
          });
        }}
        width={800}
        visible={this.state.infoModal}
      >
        <Detail meter_number={this.state.editRecord.meter_number} id={this.state.editRecord.account_id}></Detail>
      </Drawer>
    </div>;
  }
}

export default BasicList;
